const fs = require('fs');
const path = require('path');

function mkdirsSync(dirname) {  
    // console.log(dirname);
    if (fs.existsSync(dirname)) {  
        return Promise.resolve();
    } else {  
        if (mkdirsSync(path.dirname(dirname))) {  
            fs.mkdirSync(dirname);  
            return Promise.resolve();  
        }  
    }  
} 

function transform(base64Source, pathDir, file){
    let base64Data = base64Source.replace(/^data:image\/\w+;base64,/, "");
    let dataBuffer = new Buffer(base64Data, 'base64');
    return mkdirsSync(pathDir)
    .then(function(result){
        return new Promise((resolve, reject) => {
            fs.writeFile(path.join(pathDir, file), dataBuffer, err => {
                console.log(path.join(pathDir, file))
                return err ? reject(err) : resolve()
            })
        })
    })
    .catch(console.error)
}

function rename(oldPath, newPath, newFileName) {  
    return mkdirsSync(newPath)
    .then(function(result){
        return new Promise((resolve, reject) => {
            fs.rename(oldPath, path.join(newPath, newFileName), function(err){
                if(err){
                    reject(err)
                } else {
                    resolve()
                }
            })
        })
    })
} 

module.exports = {
    transform,
    rename,
}